package visualizer.google;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonRequest {
	private String referer;
	
	public JsonRequest(String referer)
	{
		this.referer = referer;
	}
	
	/**
	 * Performs an HTTP request to a given URL and returns the response as a
	 * JSONObject
	 */
	public JSONObject execute(URL resource)
	{
		URLConnection connection;
		
		try {
			connection = resource.openConnection();
		} catch (IOException e) {
			return new JSONObject();
		}
		
		connection.addRequestProperty("Referer", referer);
		String content = retrieve(connection);
		
		try {
			return new JSONObject(content);
		} catch (JSONException e) {
			return new JSONObject();
		}
	}
	
	/**
	 * Read the output from an open connection into a string
	 */
	protected String retrieve(URLConnection connection)
	{
		StringBuilder builder = new StringBuilder();
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
			// Return whatever was accumulated in the builder even in the case of an error
		}
		
		return builder.toString();
	}
}
